package com.ittao.taoaicodeapp.controller;

import com.ittao.taoaicodeapp.service.VipRedeemCodeService;
import com.ittao.taoaicodeclient.innerservice.InnerUserService;
import com.ittao.taoaicodecommon.annotation.AuthCheck;
import com.ittao.taoaicodecommon.common.BaseResponse;
import com.ittao.taoaicodecommon.common.DeleteRequest;
import com.ittao.taoaicodecommon.common.ResultUtils;
import com.ittao.taoaicodecommon.constant.UserConstant;
import com.ittao.taoaicodecommon.exception.BusinessException;
import com.ittao.taoaicodecommon.exception.ErrorCode;
import com.ittao.taoaicodecommon.exception.ThrowUtils;
import com.ittao.taoaicodemodel.model.dto.vip.VipExchangeRequest;
import com.ittao.taoaicodemodel.model.dto.vip.VipRedeemCodeGenerateRequest;
import com.ittao.taoaicodemodel.model.dto.vip.VipRedeemCodeQueryRequest;
import com.ittao.taoaicodemodel.model.dto.vip.VipRedeemCodeUpdateRequest;
import com.ittao.taoaicodemodel.model.entity.User;
import com.ittao.taoaicodemodel.model.entity.VipRedeemCode;
import com.ittao.taoaicodemodel.model.vo.user.LoginUserVO;
import com.ittao.taoaicodemodel.model.vo.vip.VipRedeemCodeVO;
import com.mybatisflex.core.paginate.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * VIP兑换码 控制层
 *
 * @author <a href="https://gitee.com/it-heima-ht">程序员 Tao</a>
 */
@Slf4j
@RestController
@RequestMapping("/vip/redeem-code")
public class VipRedeemCodeController {

    @Resource
    private VipRedeemCodeService vipRedeemCodeService;

    /**
     * 获取当前登录用户（包含完整VIP信息）
     */
    @GetMapping("/user/info")
    public BaseResponse<LoginUserVO> getCurrentUserWithVipInfo(HttpServletRequest request) {
        User loginUser = InnerUserService.getLoginUser(request);
        LoginUserVO userWithVipInfo = vipRedeemCodeService.getLoginUserVOWithVipInfo(loginUser);
        return ResultUtils.success(userWithVipInfo);
    }

    /**
     * 兑换VIP会员
     */
    @PostMapping("/exchange")
    public BaseResponse<Boolean> exchangeVip(@RequestBody VipExchangeRequest vipExchangeRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(vipExchangeRequest == null, ErrorCode.PARAMS_ERROR);
        String vipCode = vipExchangeRequest.getVipCode();

        // 获取当前登录用户
        User loginUser = InnerUserService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);

        boolean result = vipRedeemCodeService.exchangeVip(loginUser, vipCode);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "会员兑换失败");
        return ResultUtils.success(true);
    }

    /**
     * VIP续费（使用新兑换码延长VIP时间）
     * 正确的续费逻辑：覆盖用户当前的兑换码关联，累加VIP时间
     */
    @PostMapping("/renew")
    public BaseResponse<Boolean> renewVip(@RequestBody VipExchangeRequest vipExchangeRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(vipExchangeRequest == null, ErrorCode.PARAMS_ERROR);
        String vipCode = vipExchangeRequest.getVipCode();

        // 获取当前登录用户
        User loginUser = InnerUserService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);

        boolean result = vipRedeemCodeService.renewVip(loginUser, vipCode);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "VIP续费失败");
        return ResultUtils.success(true);
    }

    /**
     * 获取用户VIP使用历史（查看历史兑换记录）
     */
    @GetMapping("/user/history")
    public BaseResponse<List<VipRedeemCodeVO>> getUserVipHistory(HttpServletRequest request) {
        User loginUser = InnerUserService.getLoginUser(request);
        List<VipRedeemCodeVO> history = vipRedeemCodeService.getUserVipHistory(loginUser.getId());
        return ResultUtils.success(history);
    }

    /**
     * 获取当前用户VIP剩余天数
     */
    @GetMapping("/user/remaining-days")
    public BaseResponse<Integer> getUserVipRemainingDays(HttpServletRequest request) {
        User loginUser = InnerUserService.getLoginUser(request);
        int remainingDays = vipRedeemCodeService.getUserVipRemainingDays(loginUser.getId());
        return ResultUtils.success(remainingDays);
    }

    /**
     * 生成VIP兑换码（仅管理员）
     */
    @PostMapping("/generate")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<VipRedeemCodeVO>> generateRedeemCodes(@RequestBody VipRedeemCodeGenerateRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);

        // 获取请求参数
        Integer count = request.getCount();
        LocalDateTime validUntil = request.getValidUntil();
        Integer vipDuration = request.getVipDuration();  // 新增VIP有效期天数参数
        String remark = request.getRemark();

        // 参数校验
        if (count == null || count <= 0 || count > 100) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "生成数量必须在1-100之间");
        }
        if (validUntil == null || validUntil.isBefore(LocalDateTime.now())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "有效期必须大于当前时间");
        }

        // VIP有效期天数校验（可选参数，为空时使用默认365天）
        if (vipDuration != null && (vipDuration < 1 || vipDuration > 3650)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "VIP有效期必须在1-3650天之间");
        }

        // 生成兑换码（传入VIP有效期天数）
        List<VipRedeemCode> redeemCodes = vipRedeemCodeService.generateRedeemCodes(count, validUntil, vipDuration, remark);
        List<VipRedeemCodeVO> redeemCodeVOList = vipRedeemCodeService.getVipRedeemCodeVOList(redeemCodes);

        return ResultUtils.success(redeemCodeVOList);
    }

    /**
     * 分页查询VIP兑换码（仅管理员）
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<VipRedeemCodeVO>> listVipRedeemCodeVOByPage(@RequestBody VipRedeemCodeQueryRequest queryRequest) {
        ThrowUtils.throwIf(queryRequest == null, ErrorCode.PARAMS_ERROR);

        // 更新过期状态
        vipRedeemCodeService.updateExpiredCodes();

        int current = queryRequest.getCurrent();
        long pageSize = queryRequest.getPageSize();

        Page<VipRedeemCode> redeemCodePage = vipRedeemCodeService.page(
                new Page<>(current, pageSize),
                vipRedeemCodeService.getQueryWrapper(queryRequest)
        );

        Page<VipRedeemCodeVO> redeemCodeVOPage = new Page<>(current, pageSize, redeemCodePage.getTotalRow());
        List<VipRedeemCodeVO> redeemCodeVOList = vipRedeemCodeService.getVipRedeemCodeVOList(redeemCodePage.getRecords());
        redeemCodeVOPage.setRecords(redeemCodeVOList);

        return ResultUtils.success(redeemCodeVOPage);
    }

    /**
     * 根据ID获取VIP兑换码（仅管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<VipRedeemCodeVO> getVipRedeemCodeVOById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        VipRedeemCode redeemCode = vipRedeemCodeService.getById(id);
        ThrowUtils.throwIf(redeemCode == null, ErrorCode.NOT_FOUND_ERROR);

        VipRedeemCodeVO redeemCodeVO = vipRedeemCodeService.getVipRedeemCodeVO(redeemCode);
        return ResultUtils.success(redeemCodeVO);
    }

    /**
     * 更新VIP兑换码（仅管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateVipRedeemCode(@RequestBody VipRedeemCodeUpdateRequest updateRequest) {
        ThrowUtils.throwIf(updateRequest == null || updateRequest.getId() == null, ErrorCode.PARAMS_ERROR);

        // 获取原兑换码信息
        VipRedeemCode existingCode = vipRedeemCodeService.getById(updateRequest.getId());
        ThrowUtils.throwIf(existingCode == null, ErrorCode.NOT_FOUND_ERROR);

        // 使用服务层的方法来更新兑换码和用户状态
        boolean result = vipRedeemCodeService.updateVipRedeemCodeWithUserStatus(updateRequest);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }

    /**
     * 删除VIP兑换码（仅管理员）
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteVipRedeemCode(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);

        // 获取原兑换码信息
        VipRedeemCode existingCode = vipRedeemCodeService.getById(deleteRequest.getId());
        ThrowUtils.throwIf(existingCode == null, ErrorCode.NOT_FOUND_ERROR);

        // 在删除兑换码之前，先恢复使用该兑换码的用户状态
        vipRedeemCodeService.restoreUserStatusByRedeemCodeId(deleteRequest.getId());

        boolean result = vipRedeemCodeService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }

    /**
     * 批量删除VIP兑换码（仅管理员）
     */
    @PostMapping("/delete/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchDeleteVipRedeemCode(@RequestBody List<Long> ids) {
        ThrowUtils.throwIf(ids == null || ids.isEmpty(), ErrorCode.PARAMS_ERROR);

        // 检查所有兑换码都存在
        List<VipRedeemCode> existingCodes = vipRedeemCodeService.listByIds(ids);
        ThrowUtils.throwIf(existingCodes.size() != ids.size(), ErrorCode.NOT_FOUND_ERROR, "部分兑换码不存在");

        // 在批量删除兑换码之前，先恢复使用这些兑换码的用户状态
        vipRedeemCodeService.batchRestoreUserStatusByRedeemCodeIds(ids);

        boolean result = vipRedeemCodeService.removeByIds(ids);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }

    /**
     * 强制过期VIP兑换码（仅管理员）
     */
    @PostMapping("/expire")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> forceExpireVipRedeemCode(@RequestBody DeleteRequest request) {
        ThrowUtils.throwIf(request == null || request.getId() <= 0, ErrorCode.PARAMS_ERROR);

        // 检查兑换码是否存在
        VipRedeemCode existingCode = vipRedeemCodeService.getById(request.getId());
        ThrowUtils.throwIf(existingCode == null, ErrorCode.NOT_FOUND_ERROR, "兑换码不存在");

        boolean result = vipRedeemCodeService.forceExpireRedeemCode(request.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "强制过期兑换码失败");

        return ResultUtils.success(true);
    }

    /**
     * 批量强制过期VIP兑换码（仅管理员）
     */
    @PostMapping("/expire/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchForceExpireVipRedeemCode(@RequestBody List<Long> ids) {
        ThrowUtils.throwIf(ids == null || ids.isEmpty(), ErrorCode.PARAMS_ERROR);

        // 检查所有兑换码都存在
        List<VipRedeemCode> existingCodes = vipRedeemCodeService.listByIds(ids);
        ThrowUtils.throwIf(existingCodes.size() != ids.size(), ErrorCode.NOT_FOUND_ERROR, "部分兑换码不存在");

        boolean result = vipRedeemCodeService.batchForceExpireRedeemCodes(ids);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "批量强制过期兑换码失败");

        return ResultUtils.success(true);
    }
}
